package com.zhongke.cotrun.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Strings;
import com.zhongke.cotrun.mapper.*;
import com.zhongke.cotrun.model.pojo.*;
import com.zhongke.cotrun.service.InnovationActivitiesService;
import com.zhongke.cotrun.service.UserInfoService;
import com.zhongke.cotrun.shiro.sys.shiro.ShiroUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("innovationActivitiesService")
public class InnovationActivitiesServiceImpl implements InnovationActivitiesService {

    @Resource
    InnovationActivitiesMapper innovationActivitiesDao; //活动mapper

    @Resource
    private RegionMapper regionMapper;  //地区配置mapper

    @Resource
    private UserInfoService userInfoService;    //用户信息mapper

    @Resource
    private DictDao dictDao;    //字典mapper

    @Resource
    private SignUpInfoMapper signUpInfoMapper;  //活动明细mapper

    @Resource
    PayMallInfoMapper payMallInfoMapper;    //商品mapper

    /**
     * 分页展示
     *
     * @param innovationActivitiesEntity
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo showByPage(InnovationActivitiesEntityVo innovationActivitiesEntity, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<InnovationActivitiesEntityVo> list = innovationActivitiesDao.search(innovationActivitiesEntity);
        PageInfo pageInfo = new PageInfo(list);
        return pageInfo;
    }

    @Override
    public PageInfo showByPageForManager(InnovationActivitiesEntityVo innovationActivitiesEntity, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<InnovationActivitiesEntityVo> list = innovationActivitiesDao.search(innovationActivitiesEntity);
        for(InnovationActivitiesEntityVo vo : list){
            parserApprovalStateLabel(vo);
            parserStateLabel(vo);
        }
        PageInfo pageInfo = new PageInfo(list);
        return pageInfo;
    }

    /**
     * 根据id查找
     *
     * @param id
     * @return
     */
    @Override
    public InnovationActivitiesEntityVo selectByID(Integer id) {
        InnovationActivitiesEntityVo entityVo = innovationActivitiesDao.selectByID(id);
        setStock(entityVo);
        return parserExtData(entityVo);
    }

    /**
     * 新增
     *
     * @param innovationActivitiesEntity
     * @return
     */
    @Transactional
    @Override
    public boolean addInnovationActivities(InnovationActivitiesEntity innovationActivitiesEntity) {
        return innovationActivitiesDao.insert(innovationActivitiesEntity);
    }

    /**
     * 逻辑删除
     *
     * @param id
     * @return
     */
    @Override
    public boolean deleteByID(Integer id) {
        return innovationActivitiesDao.deleteByID(id);
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return boolean
     */
    @Override
    public boolean deleteBatch(String ids) {
        ids = ids.replaceAll(",", "','");
        return innovationActivitiesDao.deleteBatch(ids);
    }

    /**
     * 修改
     *
     * @param innovationActivitiesEntity
     * @return
     */
    @Override
    public boolean updateByID(InnovationActivitiesEntity innovationActivitiesEntity) {
        return innovationActivitiesDao.updateByID(innovationActivitiesEntity);
    }

    @Override
    public boolean updateStatus(Integer id, Integer status) {
        return innovationActivitiesDao.updateStatus(id, status);
    }

    @Override
    public int cronJobsUpdateState2() {
        return innovationActivitiesDao.cronJobsUpdateState2();
    }

    @Override
    public boolean enbaleRegistration(Integer id) {
        return innovationActivitiesDao.enbaleRegistration(id) > 0;
    }

    @Override
    public Map<String, Object> activitiesRiseTrend(String dateType, Integer size) {
        String format;
        if ("month".equalsIgnoreCase(dateType)) {
            format = "%Y/%m";
            size = size == null ? 12 : size;
        } else if ("day".equalsIgnoreCase(dateType)) {
            format = "%Y/%m/%d";
            size = size == null ? 31 : size;
        } else {
            format = "%Y";
            size = size == null ? 10 : size;
        }
        List<InnovationActivitiesEntityVo> list = innovationActivitiesDao.activitiesRiseTrend(format, size);
        if (list.isEmpty() || "[]".equals(list.toString())) {
            return null;
        } else {
            Map<String, Object> map = new HashMap<>();
            Integer[] sdata = new Integer[list.size()];
            String[] xdata = new String[list.size()];
            for (int i = 0; i < list.size(); i++) {
                xdata[i] = list.get(i).getActivitiesTopic();
                sdata[i] = list.get(i).getCounts();
            }
            map.put("sdata", sdata);
            map.put("xdata", xdata);
            return map;
        }
    }

    @Override
    public boolean updateStatus(Integer id, Integer status, String reason) {
        return innovationActivitiesDao.updateItemStatus(id, status, reason);
    }

    @Override
    public boolean updateDemandsApprovalStatus(int approvalStatus, String s, Integer id) {
        String userName = ShiroUtils.getUserName();
        return innovationActivitiesDao.updateApprovalStatus(approvalStatus, s, id,userName);
    }

    /**
     * 审核通过并上架
     *
     * @param
     * @return
     */
    @Override
    public boolean updateApprovalStatusAndMall(int approvalStatus, String s, Integer id) {
        String userName = ShiroUtils.getUserName();
        if (innovationActivitiesDao.updateApprovalStatus(approvalStatus, s, id,userName)) {
            InnovationActivitiesEntity innovationActivitiesEntity = innovationActivitiesDao.selectByID(id);
            return payMallInfoMapper.insert(parsePayMallInfo(innovationActivitiesEntity)) > 0;
        } else
            return false;
    }

    @Override
    public int queryUnApprovalCounts() {
        return innovationActivitiesDao.queryUnApprovalCounts();
    }

    @Override
    public PageInfo queryOrderForCenter(InnovationActivitiesEntityVo innovationActivitiesEntity, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        innovationActivitiesEntity.setCreateId(ShiroUtils.getWebUserId());
        List<InnovationActivitiesEntityVo> list = innovationActivitiesDao.queryOrderForCenter(innovationActivitiesEntity);
        for (InnovationActivitiesEntityVo entity : list) {
            parserExtRegionName(entity);
        }
        return new PageInfo(list);
    }

    @Override
    public PageInfo showByPageForCenter(InnovationActivitiesEntityVo innovationActivitiesEntity, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        innovationActivitiesEntity.setCreateId(ShiroUtils.getWebUserId());
        innovationActivitiesEntity.setStatusTag(3);
        List<InnovationActivitiesEntityVo> list = innovationActivitiesDao.search(innovationActivitiesEntity);
        for (InnovationActivitiesEntityVo entity : list) {
            parserExtCreateName(entity);
            parserApprovalStateLabel(entity);
            parserStateLabel(entity);
        }
        PageInfo pageInfo = new PageInfo(list);
        return pageInfo;
    }

    @Override
    public InnovationActivitiesEntityVo getSignUpInfo(Integer id) {
        InnovationActivitiesEntityVo entityVo = innovationActivitiesDao.getSignUpInfo(id);
        return setStock(entityVo);
    }

    @Override
    public boolean closeActivities(Integer id) {
        if (innovationActivitiesDao.closeActivities(id)) {
            payMallInfoMapper.updateEnableByMainId(id.longValue(), "activities");
            return true;
        }
        return false;
    }

    //设置库存
    private InnovationActivitiesEntityVo setStock(InnovationActivitiesEntityVo entityVo) {
        if (entityVo != null) {
            Integer selectCount = signUpInfoMapper.queryStock(entityVo.getId());
            if (selectCount != null && selectCount > 0) {
                entityVo.setStock(entityVo.getRegNumber() - selectCount);
            } else {
                entityVo.setStock(entityVo.getRegNumber());
            }
            return entityVo;
        }
        return null;
    }

    //转换地区 用户名 行业 活动类型
    private InnovationActivitiesEntityVo parserExtData(InnovationActivitiesEntityVo entity) {
        if (entity == null) {
            return null;
        }
        parserExtRegionName(entity);
        parserExtCreateName(entity);
        parserActivitiesType(entity);
        parserExtIndustryName(entity);
        return entity;
    }

    //转换地区名称
    private void parserExtRegionName(InnovationActivitiesEntityVo entity){
        if (entity.getProvinceId() != null && entity.getProvinceId() >= 0) {
            Region region = regionMapper.selectByPrimaryKey(entity.getProvinceId());
            if (region != null && !Strings.isNullOrEmpty(region.getName())) {
                entity.setProvinceName(region.getName());
            }
        }
        if (entity.getCityId() != null && entity.getCityId() >= 0) {
            Region region = regionMapper.selectByPrimaryKey(entity.getCityId());
            if (region != null && !Strings.isNullOrEmpty(region.getName())) {
                entity.setCityName(region.getName());
            }
        }
        if (entity.getDistrictId() != null && entity.getDistrictId() >= 0) {
            Region region = regionMapper.selectByPrimaryKey(entity.getDistrictId());
            if (region != null && !Strings.isNullOrEmpty(region.getName())) {
                entity.setDistrictName(region.getName());
            }
        }
    }

    //转换用户名
    private void parserExtCreateName(InnovationActivitiesEntityVo entity) {
        if (entity.getCreateId() != null && entity.getCreateId() > 0) {
            UserInfo userInfo = userInfoService.selectUserInfoByid(Integer.valueOf(entity.getCreateId() + ""));
            if (userInfo != null && !Strings.isNullOrEmpty(userInfo.getRealName())) {
                entity.setCreateName(userInfo.getRealName());
            }
        }
    }
    //转换行业
    private void parserExtIndustryName(InnovationActivitiesEntityVo entity) {
        if (StringUtils.isNotEmpty(entity.getActivitiesIndustry())) {
            entity.setActivitiesIndustryName(dictDao.selectValueInCodes(entity.getActivitiesIndustry()));
        }
    }
    //转换审核状态
    private void parserApprovalStateLabel(InnovationActivitiesEntityVo entity) {
        if (entity.getApprovalStatus()!=null) {
            DictEntity dictEntity = dictDao.getItemByType("approval_state_"+entity.getApprovalStatus().toString());
            if(dictEntity!=null)
                entity.setApprovalStateLabel(dictEntity.getValue());
        }
    }
    //转换审核状态
    private void parserActivitiesType(InnovationActivitiesEntityVo entity) {
        if (entity.getApprovalStatus()!=null) {
            DictEntity dictEntity = dictDao.getByCode(entity.getActivitiesType().toString());
            if(dictEntity!=null)
                entity.setActivitiesTypeName(dictEntity.getValue());
        }
    }
    //转换审核状态
    private void parserStateLabel(InnovationActivitiesEntityVo entity) {
        if (entity.getStatus()!=null) {
            DictEntity dictEntity = dictDao.getItemByType("state_"+entity.getStatus().toString());
            if(dictEntity!=null)
                entity.setStateLabel(dictEntity.getValue());
        }
    }
    //活动转商品
    private PayMallInfo parsePayMallInfo(InnovationActivitiesEntity entity) {
        PayMallInfo info = null;
        if (entity != null) {
            info = new PayMallInfo();
            info.setCreateBy(ShiroUtils.getUserId1());//设置创建人ID
            info.setMainId(entity.getId().longValue());
            info.setTypeId(1L);
            info.setTitle(entity.getActivitiesTopic());
            info.setPrice(entity.getRegFee() == null ? 0.0 : entity.getRegFee().doubleValue());
            info.setIsEnable("1");
            info.setVolume(0);
            info.setStock(entity.getRegNumber());
        }
        return info;
    }
}

